//
//  LZVideoListForSearchViewController.m
//  laziz_Consumer
//
//  Created by xbnzd on 16/12/19.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZVideoListForSearchViewController.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "UITableView+LZTableView.h"
#import "XBNTimeLimitCountDownCalculator.h"
#import "LZVideoCellPresenter.h"
#import "LZCustomPlayerView.h"
#import "LZVideoTableViewCell.h"
#import "LZMapLocationManager.h"
#import "LZSearchRequestPresenter.h"
#import "LZPlayVideoManager.h"
#import "LAMerchantDetailViewController.h"
#import "extobjc.h"
#import "MJRefresh.h"
#import "LZNoDataPublicView.h"

static NSString *kCellIdentifer = @"maincell";

@interface LZVideoListForSearchViewController ()<LZ_MainTableViewCellDelegate,UIScrollViewDelegate,LZVideoCellDelegate,LZPlayVideoManagerDelegate,UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *videoTableView;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) LZSearchRequestPresenter *requestPresenter;
@property (nonatomic, assign) int pageNum;
@property (nonatomic, assign) NSTimeInterval timeStamp;
@property (strong, nonatomic) XBNTimeLimitCountDownCalculator *timeCountDownCalculator;
@property (nonatomic, strong) NSIndexPath *currentPlayCellIndexPath;
@property (nonatomic, strong) LZVideoCellPresenter *videoCellPresenter;
@property (nonatomic, strong) LZCustomPlayerView *playerView;
@property (nonatomic, assign) BOOL  isFirstLoad; //标记是否第一次进入.用于,其他时候返回本页面继续播放视频

@property (nonatomic, assign) NSTimeInterval request_timeStemp;

@end

@implementation LZVideoListForSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.umLogPageViewName = @"视频列表搜索页面";
    
    [self configureUI];
    
    [self getVideoListAction];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self releasePlayViewRAM];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [LZPlayVideoManager shareManager].playVideoManagerDelegate = self;
    
    if (self.isFirstLoad == NO) {
        WS(weakSelf);
        self.currentPlayCellIndexPath = [[LZPlayVideoManager shareManager] goOnPlayWithCellIndexPath:self.currentPlayCellIndexPath playerView:self.playerView tableView:self.videoTableView playCountAddBlock:^(NSInteger totleCount) {
            [weakSelf addViewsCountWithIndexPath:weakSelf.currentPlayCellIndexPath withCount:totleCount];
        }];
    }
    
    self.isFirstLoad = NO;
}

#pragma mark -
#pragma mark private
/**
 离开页面,释放播放器内存
 */
- (void)releasePlayViewRAM
{
    [[LZPlayVideoManager shareManager] stopPlayWithPlayerView:self.playerView];
}

/**
 添加浏览次数
 
 @param indexP <#indexP description#>
 @param totleCount <#totleCount description#>
 */
- (void)addViewsCountWithIndexPath:(NSIndexPath *)indexP withCount:(NSInteger)totleCount
{
    LZVideoListModel *m = self.dataArr[self.currentPlayCellIndexPath.row];
    m.playCount = totleCount;
    LZVideoTableViewCell *cell = [self.videoTableView cellForRowAtIndexPath:indexP];
    [cell getViewsCountLabel].text = [NSString stringWithFormat:@"%ld",(long)totleCount];
}

/**
 上拉加载
 */
- (void)upLoadMoreVideoListData
{
    [self getVideoListAction];
}

- (void)getVideoListAction
{
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    
    if ([LZMapLocationManager shareLocationManager].currentLocation != nil) {
        double lat = [LZMapLocationManager shareLocationManager].currentLocation.coordinate.latitude;
        double lon = [LZMapLocationManager shareLocationManager].currentLocation.coordinate.longitude;
        dic[@"mapLocationLatitude"] = [NSNumber numberWithDouble:lat];
        dic[@"mapLocationLongitude"] = [NSNumber numberWithDouble:lon];
    }
    
    dic[@"type"] = self.searchType;
    
    dic[@"timestamp"] = [NSNumber numberWithLong:self.request_timeStemp];
    
    if ([self.searchType isEqualToString:@"1"]) {
        // 如果type为1的时候（菜系）则"name"值传 id
        dic[@"name"] = self.searchId;
    }
    else {
        dic[@"name"] = self.searchMessage;
    }
    
    @weakify(self);
    
    [self.requestPresenter searchPromotionVideoListWithPrameter:dic andPage:self.pageNum andLimit:10 onSuccess:^(NSArray *listArr, int totlePage, int totleCount, NSTimeInterval timeStamp) {
        @strongify(self);
        
        if (self.timeStamp <= 0) {
            self.timeStamp = timeStamp/1000;
        }
        
        if (self.request_timeStemp <= 0) {
            self.request_timeStemp = timeStamp;
        }
        
        [self.dataArr addObjectsFromArray:listArr];
        if (self.pageNum < totlePage) {
            [self.videoTableView.mj_footer endRefreshing];
        }else{
            if (self.dataArr.count == 0) {
                [self.videoTableView setNullStringFooterText];
            }
            else {
                [self.videoTableView setNoMoreDataFooterText];
            }
            [self.videoTableView.mj_footer endRefreshingWithNoMoreData];
        }
        
        if (self.dataArr.count == 0) {
            [LZNoDataPublicView showNoDataViewInView:self.videoTableView];
            [self.timeCountDownCalculator timeLimitCountDownClear];
            self.timeCountDownCalculator = nil;
            [self releasePlayViewRAM];
        }
        else {
            [LZNoDataPublicView hiddenNoDataViewInView:self.videoTableView];
        }
        
        [self.videoTableView fd_reloadDataWithoutInvalidateIndexPathHeightCache];
        
        self.pageNum ++;

        //默认播放第一个视频
        if (self.pageNum == 1 && self.dataArr.count != 0) {
            self.currentPlayCellIndexPath = [[LZPlayVideoManager shareManager] playVideoWhenTableViewStopScrollWithTableView:self.videoTableView cellIndexPath:self.currentPlayCellIndexPath playerView:self.playerView playCountAddBlock:^(NSInteger totleCount) {
                [self addViewsCountWithIndexPath:self.currentPlayCellIndexPath withCount:totleCount];
            }];
        }
    } onFail:^(NSString *fail) {
        @strongify(self);
        [self.timeCountDownCalculator timeLimitCountDownClear];
        self.timeCountDownCalculator = nil;
        [self.videoTableView.mj_footer endRefreshing];
    }];
}

#pragma mark -
#pragma mark currentTimer 倒计时相关
- (void)setTimeStamp:(NSTimeInterval)timeStamp
{
    _timeStamp = timeStamp;
    // 开起计时器
    [self startTimeCountDown];
}

- (void)startTimeCountDown {
    if (self.timeCountDownCalculator) {
        return;
    }
    // ******************** 创建计时器 ********************
    self.timeCountDownCalculator = [XBNTimeLimitCountDownCalculator new];
    
    // 取出服务器时间
    self.timeCountDownCalculator.remainTimeInterval = self.timeStamp;
    
    // 以服务器时间为标准时间开始计算
    WS(weakSelf);
    [self.timeCountDownCalculator addProcessBlock:^(NSTimeInterval remain) {
        weakSelf.timeStamp += 1;
    } cancelBlock:^{
        DLog(@"结束了");
    }];
    
    [self.timeCountDownCalculator timeLimitCountDownResume];
    
}



#pragma mark -
#pragma mark configure UI
- (void)configureUI
{
    _pageNum = 1;
    _timeStamp = 0;
    _request_timeStemp = 0;
    _dataArr = @[].mutableCopy;
    _requestPresenter = [[LZSearchRequestPresenter alloc] init];
    _videoCellPresenter = [[LZVideoCellPresenter alloc] init];
    _playerView = [[LZCustomPlayerView alloc] init];
    _playerView.playCircle = YES;
    _isFirstLoad = YES;
    
    [self.videoTableView registerClass:[LZVideoTableViewCell class] forCellReuseIdentifier:kCellIdentifer];
    
    self.videoTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upLoadMoreVideoListData)];
    [self.videoTableView configFooterRefreshText];
    
    self.videoTableView.delegate = self;
    self.videoTableView.dataSource = self;
}

#pragma mark -
#pragma mark tableview delegate datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LZVideoListModel *m = self.dataArr[indexPath.row];
    return [tableView fd_heightForCellWithIdentifier:kCellIdentifer cacheByKey:m.videoId configuration:^(id cell) {
        LZVideoTableViewCell *cellTemp = (LZVideoTableViewCell *)cell;
        [cell loadDataWithIndex:indexPath WithShowHeadView:YES showCellBtns:YES showCouponAndGroupsView:YES];
        cellTemp.model = m;
        
    }];
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LZVideoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifer];
    if (cell == nil) {
        cell = [[LZVideoTableViewCell  alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellIdentifer];
    }
    LZVideoListModel *m = self.dataArr[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.mainDelegate = self;
    cell.cellClickDelegate = self;
    [cell loadDataWithIndex:indexPath WithShowHeadView:YES showCellBtns:YES showCouponAndGroupsView:YES];
    m.currentTime = self.timeStamp;
    cell.model = m;
    [cell startTimeDown];
    
    return cell;
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if(!decelerate){//缓慢拖动.手指离开时
        WS(wSelf);
        self.currentPlayCellIndexPath = [[LZPlayVideoManager shareManager] playVideoWhenTableViewStopScrollWithTableView:self.videoTableView cellIndexPath:self.currentPlayCellIndexPath playerView:self.playerView playCountAddBlock:^(NSInteger totleCount) {
            [wSelf addViewsCountWithIndexPath:wSelf.currentPlayCellIndexPath withCount:totleCount];
        }];
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    WS(wSelf);
    self.currentPlayCellIndexPath = [[LZPlayVideoManager shareManager] playVideoWhenTableViewStopScrollWithTableView:self.videoTableView cellIndexPath:self.currentPlayCellIndexPath playerView:self.playerView playCountAddBlock:^(NSInteger totleCount) {
       [wSelf addViewsCountWithIndexPath:wSelf.currentPlayCellIndexPath withCount:totleCount];
    }];
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //滑动时判断当前播放的cell是否已经离开屏幕.已经离开,停止播放
    [[LZPlayVideoManager shareManager] removePlayViewWhenTableViewDidScrollWithTableView:self.videoTableView cellIndexPath:self.currentPlayCellIndexPath];
}

#pragma mark -
#pragma mark cell  delegate
/**
 cell 按钮协议方法
 index: 0点赞 1收藏  2信息  3分享   4视频详情  5抢券详情   6拼团详情
 */

- (void)clickCellButtonWithIndex:(VideoCellDelegateClickEventCode)index andCellIndexPath:(NSIndexPath *)cellIndexPath andModel:(id)model andOtherObject:(id)object refreshBlock:(void (^)(VideoCellRefreshType, BOOL))refreshBlock {
   
    
    if (index == kVideoCellDelegate_restaurantDetailEvent) {
        LZVideoListModel *m = (LZVideoListModel *)model;
        LAMerchantDetailViewController *vc = [[LAMerchantDetailViewController alloc] init];
        vc.restaurantId = [m.sellerId copy];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
        
    }else{
         [self.videoCellPresenter dealClickCellButtonIndex:index andCellIndexPath:cellIndexPath andNavigationController:self.navigationController andHidesBottomBarWhenPushed:YES andCellModel:model andOtherObject:object andRefreshBlcok:refreshBlock];
    }
}

/**
 点击视频海报播放协议
 */
- (void)playVideoWhenClickVideoCoverImgWithIndex:(NSIndexPath *)cellIndexPath
{
    [self.videoTableView scrollToRowAtIndexPath:cellIndexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
    WS(wSelf);
    self.currentPlayCellIndexPath = [[LZPlayVideoManager shareManager] playVideoWhenClickVideoCoverImgWithIndexPath:cellIndexPath playerView:self.playerView playCountAddBlock:^(NSInteger totleCount) {
        [wSelf addViewsCountWithIndexPath:cellIndexPath withCount:totleCount];
    }];
    
}

#pragma mark -
#pragma mark  播放控制器获取资源delegate
- (NSString *)playVideoManagerGetVideoUrlWith:(NSIndexPath *)cellIndexPath
{
    LZVideoListModel *m = self.dataArr[cellIndexPath.row];
    
    return m.videoUrl;
}

- (UIView *)playVidewManagerGetPlayBackgroundViewWith:(NSIndexPath *)cellIndexPath
{
    LZVideoTableViewCell *cell = [self.videoTableView cellForRowAtIndexPath:cellIndexPath];
    
    return cell.playerBgView;
}

- (NSString *)playVideoManagerGetVideoIdWithIndexPath:(NSIndexPath *)cellIndexPath
{
    LZVideoListModel *m = self.dataArr[cellIndexPath.row];
    
    return m.videoId;
}




@end
